package com.studysystem.controller;

import com.studysystem.dto.DiscussionPostRequest;
import com.studysystem.dto.DiscussionCommentRequest;
import com.studysystem.entity.DiscussionComment;
import com.studysystem.entity.DiscussionPost;
import com.studysystem.entity.User;
import com.studysystem.repository.DiscussionCommentRepository;
import com.studysystem.repository.DiscussionPostRepository;
import com.studysystem.repository.CourseRepository;
import com.studysystem.repository.UserRepository;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/discussion")
public class DiscussionController {
    private final DiscussionPostRepository postRepository;
    private final DiscussionCommentRepository commentRepository;
    private final CourseRepository courseRepository;
    private final UserRepository userRepository;

    public DiscussionController(DiscussionPostRepository postRepository, DiscussionCommentRepository commentRepository, CourseRepository courseRepository, UserRepository userRepository) {
        this.postRepository = postRepository;
        this.commentRepository = commentRepository;
        this.courseRepository = courseRepository;
        this.userRepository = userRepository;
    }

    // 获取课程讨论区帖子列表
    @GetMapping("/{courseId}/posts")
    public List<DiscussionPost> getPosts(@PathVariable Long courseId) {
        List<DiscussionPost> posts = postRepository.findByCourseId(courseId);
        for (DiscussionPost post : posts) {
            post.setComments(new java.util.HashSet<>(commentRepository.findByPostId(post.getId())));
        }
        return posts;
    }

    // 获取单个帖子详情（含评论）
    @GetMapping("/post/{postId}")
    public DiscussionPost getPost(@PathVariable Long postId) {
        return postRepository.findById(postId).orElse(null);
    }

    // 发表新帖子
    @PostMapping("/{courseId}/post")
    public String createPost(@AuthenticationPrincipal UserDetails userDetails, @PathVariable Long courseId, @RequestBody DiscussionPostRequest request) {
        Optional<User> userOpt = userRepository.findByUsername(userDetails.getUsername());
        if (userOpt.isEmpty()) return "用户不存在";
        User user = userOpt.get();
        DiscussionPost post = new DiscussionPost();
        post.setTitle(request.getTitle());
        post.setContent(request.getContent());
        post.setUser(user);
        post.setCourse(courseRepository.findById(courseId).orElse(null));
        post.setCreatedAt(LocalDateTime.now());
        post.setUpdatedAt(LocalDateTime.now());
        postRepository.save(post);
        return "发帖成功";
    }

    // 对帖子发表评论/回复
    @PostMapping("/comment")
    public String createComment(@AuthenticationPrincipal UserDetails userDetails, @RequestBody DiscussionCommentRequest request) {
        User user;
        if (userDetails == null) {
            user = userRepository.findByUsername("anonymous").orElseGet(() -> {
                User anon = new User();
                anon.setUsername("anonymous");
                anon.setPassword("anonymous");
                anon.setEmail("anonymous@system.com");
                anon.setFullName("匿名用户");
                return userRepository.save(anon);
            });
        } else {
            Optional<User> userOpt = userRepository.findByUsername(userDetails.getUsername());
            if (userOpt.isEmpty()) return "用户不存在";
            user = userOpt.get();
        }
        DiscussionComment comment = new DiscussionComment();
        comment.setContent(request.getContent());
        comment.setUser(user);
        if (request.getPostId() != null) {
            comment.setPost(postRepository.findById(request.getPostId()).orElse(null));
        }
        if (request.getParentCommentId() != null) {
            comment.setParentComment(commentRepository.findById(request.getParentCommentId()).orElse(null));
        }
        comment.setCreatedAt(LocalDateTime.now());
        comment.setUpdatedAt(LocalDateTime.now());
        commentRepository.save(comment);
        return "评论成功";
    }

    // 获取所有讨论区帖子（不区分课程）
    @GetMapping("/all")
    public List<DiscussionPost> getAllPosts() {
        List<DiscussionPost> posts = postRepository.findAll();
        for (DiscussionPost post : posts) {
            post.setComments(new java.util.HashSet<>(commentRepository.findByPostId(post.getId())));
        }
        return posts;
    }

    // 获取所有评价（所有discussion_comments）
    @GetMapping("/allComments")
    public List<DiscussionComment> getAllComments() {
        return commentRepository.findAll();
    }
} 